package com.lbd.gulimall.ware.service.impl;

import com.lbd.common.constrant.WareConstrant;
import com.lbd.gulimall.ware.entity.PurchaseDetailEntity;
import com.lbd.gulimall.ware.service.PurchaseDetailService;
import com.lbd.gulimall.ware.service.WareSkuService;
import com.lbd.gulimall.ware.vo.MergeVO;
import com.lbd.gulimall.ware.vo.PurchaseDetailVO;
import com.lbd.gulimall.ware.vo.PurchaseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lbd.common.utils.PageUtils;
import com.lbd.common.utils.Query;

import com.lbd.gulimall.ware.dao.PurchaseDao;
import com.lbd.gulimall.ware.entity.PurchaseEntity;
import com.lbd.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", WareConstrant.PurchaseStatusEnum.ASSIGNED.getCode())
                        .or()
                        .eq("status", WareConstrant.PurchaseStatusEnum.CREATED.getCode())
        );

        return new PageUtils(page);
    }

    @Override
    public int merge(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        //如果没有选择采购单ID，就新建一个采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstrant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        //确认采购单状态是0/1才能合并
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        if (purchaseEntity.getStatus() == WareConstrant.PurchaseStatusEnum.CREATED.getCode()
                || purchaseEntity.getStatus() == WareConstrant.PurchaseStatusEnum.ASSIGNED.getCode()) {
            //合并采购需求其实就是为wms_purchase_detail绑定上对应的采购单id即可
            List<Long> items = mergeVO.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstrant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntities);
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public PageUtils queryByCondition(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("status", status);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(item -> {
                item.eq("id", key).or().like("assignee_name", key);
            });
        }
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void received(Long[] purchaseIds) {
        List<Long> list = new ArrayList<>();
        if (purchaseIds.length > 0) {
            list = Arrays.asList(purchaseIds);
        }
        //1. 判断当前采购单是否是已分配状态，是的话才可以拾取
        List<PurchaseEntity> purchaseEntities = list.stream()
                .map(purchaseId -> this.getById(purchaseId))
                .filter(purchaseEntity -> {
                    if (purchaseEntity.getStatus() == WareConstrant.PurchaseStatusEnum.CREATED.getCode()
                            || purchaseEntity.getStatus() == WareConstrant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    } else {
                        return false;
                    }
                })
                .map(purchaseEntity -> {
                    purchaseEntity.setStatus(WareConstrant.PurchaseStatusEnum.RECEIVE.getCode());
                    return purchaseEntity;
                })
                .collect(Collectors.toList());
        //2. 被领取后修改采购单状态
        if (purchaseEntities != null && purchaseEntities.size() > 0) {
            this.updateBatchById(purchaseEntities);
            //3. 修改采购单需求状态
            List<Long> eligibleIds = purchaseEntities.stream()
                    .map(purchaseEntity -> purchaseEntity.getId())
                    .collect(Collectors.toList());
            if (eligibleIds != null && eligibleIds.size() > 0) {
                //查出当前采购单关联的所有采购需求
                List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService
                        .list(new QueryWrapper<PurchaseDetailEntity>().in("purchase_id", eligibleIds));
                if (purchaseDetailEntities !=null && purchaseDetailEntities.size() > 0) {
                    List<PurchaseDetailEntity> purchaseDetailEntities1 = purchaseDetailEntities.stream().map(purchaseDetailEntity -> {
                        purchaseDetailEntity.setStatus(WareConstrant.PurchaseDetailStatusEnum.BUYING.getCode());
                        return purchaseDetailEntity;
                    }).collect(Collectors.toList());
                    if (purchaseDetailEntities1 !=null && purchaseDetailEntities1.size() > 0)
                    purchaseDetailService.updateBatchById(purchaseDetailEntities1);
                }
            }
        }
    }


    @Transactional
    @Override
    public int done(PurchaseVO purchaseVO) {
        //TODO: 异常的操作在后续MQ解决分布式事务一致性时处理
        Long id = purchaseVO.getId();
        if (this.getById(id).getStatus() == WareConstrant.PurchaseStatusEnum.RECEIVE.getCode()) {
            //修改每一条采购单的状态
            Boolean flag = true;
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            List<PurchaseDetailVO> purchaseDetails = purchaseVO.getItems();
            for (PurchaseDetailVO purchaseDetail : purchaseDetails) {
                if (purchaseDetail.getStatus() == WareConstrant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                    flag = false;
                    purchaseDetailEntity.setStatus(WareConstrant.PurchaseDetailStatusEnum.HASERROR.getCode());
                }else {
                    purchaseDetailEntity.setStatus(WareConstrant.PurchaseDetailStatusEnum.FINISH.getCode());
                    //已完成商品入库，ware-sku。需要考虑库中是否有商品库存记录，没有就新增，有就修改
                    PurchaseDetailEntity purchaseDetailEntity1 = purchaseDetailService.getById(purchaseDetail.getItemId());
                    wareSkuService.addStock(purchaseDetailEntity1.getSkuId(),purchaseDetailEntity1.getWareId(),purchaseDetailEntity1.getSkuNum());
                }
                purchaseDetailEntity.setId(purchaseDetail.getItemId());
                purchaseDetailService.updateById(purchaseDetailEntity);
            }
            //改变采购单状态。只有所有采购单条目都顺利完成，采购单状态才能置为已完成。否则置为有异常
            PurchaseEntity purchaseEntity = this.getById(id);
            purchaseEntity.setStatus(flag?WareConstrant.PurchaseStatusEnum.FINISH.getCode():WareConstrant.PurchaseStatusEnum.HASERROR.getCode());
            this.updateById(purchaseEntity);
            return 1;
        }else {
            return 0;
        }
    }

}